import React, { PureComponent } from 'react'
import { connect } from "react-redux";
import dayjs from "dayjs";
import notify from "@utils/tip";
import { Tabs, Button, Select } from 'antd'
const TabPane = Tabs.TabPane;
import DoubleCheck from "@common/presentational/DoubleCheck";
import { withRouter } from "react-router-dom";
import { getQuery, handleQueryEqual, setQuery } from "@utils/setUrlQuery";
import { WarehouseSelect } from '@components/warehouse/WarehouseSelect'
import { AllWarehouseSelect } from '@components/warehouse/AllWarehouseSelect'
import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from "@common/presentational/CustomizeTable";
import { WAREHOUSE_SCHEDULE_LIST, WAREHOUSE_SCHEDULE_STATUS } from "@constants/WarehouseOrderStatus";
import {
    getWarehouseScheduleIn,
    getWarehouseScheduleOut,
    getWarehouseScheduleInfo,
    creatScheduleReview,
} from "@sagas/warehouse/schedule";
import BilinIcon from "@common/presentational/BilinIcon";
import DateRangePicker from "@common/presentational/DateRangePicker";
import ParamsInput from "@common/presentational/ParamsInput";
@connect(({ warehouseManagement, schedule }) => ({
    warehouseScheduleList: schedule.warehouseScheduleList,
    selectedWarehouse: warehouseManagement.selectedWarehouse,
    warehouseSelection: warehouseManagement.warehouseSelection,
}), {
    getWarehouseScheduleIn,
    getWarehouseScheduleOut,
    getWarehouseScheduleInfo,
    creatScheduleReview
})
@withRouter
class ScheduleManage extends PureComponent {
    constructor(props) {
        super(props);
        const {
            startDate = dayjs().subtract(1, 'month').add(1, 'days').format('YYYY-MM-DD'),
            endDate = dayjs().format('YYYY-MM-DD'),
            warehouseId = props.selectedWarehouse,
            outWarehouseId = '',
            status = '',
            queryOrderNumber = '',
            activeTab = 'in',
        } = getQuery(props.history)
        this.state = {
            activeTab,
            startDate,
            endDate,
            warehouseId,
            outWarehouseId,
            status,
            queryOrderNumber,
        }

        this.changeTab = this.changeTab.bind(this)
        this.tableRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)
        this.paginationInfo = {}
        this.goSchedule = this.goSchedule.bind(this)
    }

    changeTab(key) {
        this.setState({
            activeTab: key,
        },this.initTable)
    }

    refuse(record) {
        const { creatScheduleReview } = this.props
        const { warehouseId } = this.state
        creatScheduleReview({
            id:warehouseId,
            orderNumber: record.order_number,
            status: 0
        },()=>{
            this.getTableInfo()
        })
    }

    agree(record) {
        const { warehouseId } = this.state
        const { history } = this.props
        this.props.getWarehouseScheduleInfo({
            id: warehouseId,
            orderNumber: record.order_number
        }, (res) => {
            history.push({
                pathname: `/warehouse/schedule-agree/${record.order_number}`,
                state: {
                    ...res
                }
            })
        })
    }

    inStorage(record) {
        const { warehouseId } = this.state
        const { history } = this.props
        this.props.getWarehouseScheduleInfo({
            id: warehouseId,
            orderNumber: record.order_number
        }, (res) => {
            history.push({
                pathname: `/warehouse/schedule-in/${record.order_number}`,
                state: {
                    ...res
                }
            })
        })
    }

    goDetail(record) {
        const { warehouseId } = this.state
        const { history } = this.props
        this.props.getWarehouseScheduleInfo({
            id: warehouseId,
            orderNumber: record.order_number
        }, (res) => {
            history.push({
                pathname: `/warehouse/schedule-detail/${record.order_number}`,
                state: {
                    ...res
                }
            })
        })
    }

    renderListOperation(record) {
        const { activeTab } = this.state
        if(activeTab === 'in'){
            switch (record.status) {
                // 1 待审核
                // 2 已审核（已调出）
                case 2:
                    return (
                        <div className='flex-vertical-center'>
                            <div onClick={this.inStorage.bind(this, record)} className="mgr-8 ft-hover">入库</div>
                            <div onClick={this.goDetail.bind(this, record)} className="mgr-8 ft-hover">详情</div>
                        </div>
                    )
                // 3 已入库 
                // 4 已拒绝 
                default:
                    return (
                        <div className='flex-vertical-center'>
                            <div onClick={this.goDetail.bind(this, record)} className="mgr-8 ft-hover">详情</div>
                        </div>
                    )
            }
        }else{
            switch (record.status) {
                // 1 待审核
                case 1:
                    return (
                        <div className='flex-vertical-center'>
                            <div onClick={this.agree.bind(this, record)} className="mgr-8 ft-hover">同意</div>
                            <DoubleCheck title='确定拒绝调拨？' onClick={this.refuse.bind(this, record)}>
                                <div className="mgr-8 ft-hover">拒绝</div>
                            </DoubleCheck>
                            <div onClick={this.goDetail.bind(this, record)} className="mgr-8 ft-hover">详情</div>
                        </div>
                    )
                // 2 已审核（已调出）
                // 3 已入库 
                // 4 已拒绝 
                default:
                    return (
                        <div className='flex-vertical-center'>
                            <div onClick={this.goDetail.bind(this, record)} className="mgr-8 ft-hover">详情</div>
                        </div>
                    )
            }
        }
    }

    handleValueChange(key, value) {
        if (key === 'dateRange') {
            this.setState({
                ...value
            }, this.initTable)
            return;
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    getTableInfo({ current, pageSize } = this.paginationInfo) {
        const { getWarehouseScheduleOut, getWarehouseScheduleIn } = this.props
        this.paginationInfo = { current, pageSize }
        const { startDate, endDate, status, queryOrderNumber, warehouseId, outWarehouseId, activeTab } = this.state
        const params = {
            id: warehouseId,
            startDate,
            endDate,
            status,
            queryOrderNumber,
            pageNo: current,
            pageSize,
        }
        if(outWarehouseId && activeTab === 'in'){
            params.outWarehouseId = outWarehouseId
        }
        if(outWarehouseId && activeTab === 'out'){
            params.inWarehouseId = outWarehouseId
        }
        if(activeTab === 'in'){
            warehouseId && getWarehouseScheduleIn(params)
        }else{
            warehouseId && getWarehouseScheduleOut(params)
        }
        this.setUrlQuery()
    }

    goSchedule() {
        this.props.history.push(`/warehouse/schedule-create`)
    }

    initTable() {
        this.tableRef.current?.initPage()
    }

    setUrlQuery() {
        const { current, pageSize } = this.paginationInfo
        const { startDate, endDate, status, queryOrderNumber, warehouseId, outWarehouseId } = this.state
        const { history } = this.props
        let params = {
            startDate, endDate,
            status,
            queryOrderNumber,
            warehouseId, outWarehouseId, current, pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    render() {
        const { warehouseScheduleList, warehouseSelection } = this.props
        const { activeTab, startDate, endDate, status, queryOrderNumber, warehouseId, outWarehouseId } = this.state
        const columns = [{
            title: '单据编号',
            dataIndex: 'order_number',
            key: 'order_number',
            width: '300px'
        }, {
            title: '申请时间',
            dataIndex: 'apply_time',
            key: 'apply_time',
        }, {
            title: activeTab === 'in' ?'发货方' : '调拨申请方',
            dataIndex: activeTab === 'in' ? 'out_warehouse_name' :'in_warehouse_name',
            key: activeTab === 'in' ? 'out_warehouse_name' :'in_warehouse_name',
        }, {
            title: '申请项数',
            dataIndex: 'detail_count',
            key: 'detail_count',
        }, {
            title: activeTab === 'in' ? '入库时间' :'调出时间',
            dataIndex: activeTab === 'in' ? 'receive_time' :'send_time',
            key: activeTab === 'in' ? 'receive_time' :'send_time',
        }, {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width:180,
            render: (text, record) => {
                let statusStr = WAREHOUSE_SCHEDULE_STATUS[text]
                if (record.storage_status === 1 && activeTab === 'out') {
                    return (
                        <>
                            <div className="text-center">{statusStr}</div>
                            <div className="text-center clr-orange">(部分商品库存不足)</div>
                        </>
                    )
                }else{
                    return (
                        <>
                            <div className="text-center">{statusStr}</div>
                        </>
                    )
                }
            }
        }, {
            title: '操作',
            dataIndex: 'operation',
            key: 'operation',
            render: (text, record) => this.renderListOperation(record)
        }]
        return (
            <>
                <Button type="primary" className="button-small mgb-16" onClick={this.goSchedule} ><BilinIcon type="plus" className="ft-18 mgr-8"/>新建调拨单</Button>
                <Tabs
                    type="card"
                    activeKey={activeTab}
                    onChange={this.changeTab}
                    className='schedule-manage-tabs'
                >
                    <TabPane tab="调入管理" key="in">
                    </TabPane>
                    <TabPane tab="调出管理" key="out">
                    </TabPane>
                </Tabs>
                <div className="table-scroll-container warehouse-order-page" style={{ height: 'calc(100% - 110px)' }}>
                    <div className="table-params page-params flex-vertical-center mgb-16">
                        <span className='mgr-8'>当前仓库:</span>
                        <WarehouseSelect
                            value={warehouseId}
                            onChange={this.handleValueChange.bind(this, 'warehouseId')}
                        />
                        <DateRangePicker
                            className="mgl-16"
                            startDate={startDate}
                            endDate={endDate}
                            onChange={this.handleValueChange.bind(this, 'dateRange')}
                            beforeNow
                        />
                        <span className='mgl-8 mgr-8'>{activeTab === 'in' ?'调出仓库:' : '调入仓库:'}</span>
                        <AllWarehouseSelect
                            value={outWarehouseId}
                            onChange={this.handleValueChange.bind(this, 'outWarehouseId')}
                        />
                        <Select
                            className="mgl-16"
                            style={{ width: '140px' }}
                            placeholder="请选择状态"
                            allowClear={true}
                            value={status}
                            onChange={this.handleValueChange.bind(this, 'status')}
                            filterOption={(input, option) => option.props.children.indexOf(input) >= 0}
                        >
                            {(WAREHOUSE_SCHEDULE_LIST || []).map(item => {
                                return <Select.Option key={item.id} value={item.id} >{item.name}</Select.Option>
                            }) }
                        </Select>
                        <ParamsInput
                            className="mgl-16"
                            style={{ width: '200px' }}
                            value={queryOrderNumber}
                            onChange={this.handleValueChange.bind(this, 'queryOrderNumber')}
                            placeholder="订单编号"
                        />
                    </div>
                    <CustomizeTableProvide ref={this.tableRef} tableKey="warehouseOrderList" onChange={this.getTableInfo}>
                        <div className="table-list">
                            <CustomizeTable
                                columns={columns}
                                dataSource={warehouseScheduleList.orders || []}
                                pagination
                            />
                        </div>
                        <div className="table-pagination">
                            <CustomizeTablePagination
                                total={warehouseScheduleList.total}
                            />
                        </div>
                    </CustomizeTableProvide>
                </div>
            </>
        )
    }
}

export default ScheduleManage